package com.battery.web.controller.system.battery;

import java.math.BigDecimal;
import java.util.List;

import com.battery.common.enums.AccountTypeEnum;
import com.battery.common.enums.YesOrNoEnum;
import com.battery.common.utils.DateUtils;
import com.battery.common.utils.MobileEmailUtils;
import com.battery.system.domain.ProxyUser;
import com.battery.system.domain.VO.ProjectVO;
import com.battery.system.service.battery.IProjectService;
import com.battery.system.service.battery.IProxyUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.battery.common.annotation.Log;
import com.battery.common.enums.BusinessType;
import com.battery.system.domain.Project;
import com.battery.common.core.controller.BaseController;
import com.battery.common.core.domain.AjaxResult;
import com.battery.common.utils.poi.ExcelUtil;
import com.battery.common.core.page.TableDataInfo;

/**
 * 项目Controller
 *
 * @author battery
 * @date 2021-01-20
 */
@Controller
@RequestMapping("/system/project")
public class ProjectController extends BaseController {


    private String prefix = "system/project";

    @Autowired
    private IProjectService projectService;


    @Autowired
    private IProxyUserService proxyUserService;

    @Autowired
    private Sid sid;

    @RequiresPermissions("system:project:view")
    @GetMapping()
    public String project() {
        return prefix + "/project";
    }

    /**
     * 查询项目列表
     */
    @RequiresPermissions("system:project:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Project project) {
        startPage();
//        List<Project> list = projectService.selectProjectList(project);
        List<ProjectVO> list = projectService.selectProjectVOList(project);
        return getDataTable(list);
    }


    @RequiresPermissions("system:project:queryAccount")
    @PostMapping("/accountlist")
    @ResponseBody
    public TableDataInfo accountlist(ProxyUser proxyUser) {
        startPage();
        List<ProxyUser> list = proxyUserService.selectProxyUserList(proxyUser);
        return getDataTable(list);
    }


    /**
     * 导出项目列表
     */
    @RequiresPermissions("system:project:export")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Project project) {
        List<Project> list = projectService.selectProjectList(project);
        ExcelUtil<Project> util = new ExcelUtil<Project>(Project.class);
        return util.exportExcel(list, "project");
    }

    /**
     * 新增项目
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存项目
     */
    @RequiresPermissions("system:project:add")
    @Log(title = "项目", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Project project) {
        return toAjax(projectService.insertProject(project));
    }

    /**
     * 修改项目
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        Project project = projectService.selectProjectById(id);
        mmap.put("project", project);
        return prefix + "/edit";
    }


    /**
     * 平台-项目添加APP账号
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/addAccount/{id}")
    public String addAccount(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("projectId", id);
        return prefix + "/addAccount";
    }

    /**
     * 查看APP账号列表
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/queryAccount/{id}")
    public String queryAccount(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("accountId", id);
        mmap.put("accountType", AccountTypeEnum.PROJECT.getCode());
        return prefix + "/queryAccount";
    }


    /**
     * t添加APP登录账号
     */
    @RequiresPermissions("system:project:addAccount")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PostMapping("/addAccount")
    @ResponseBody
    public AjaxResult addAccount(ProxyUser proxyUser) {


        if (StringUtils.isBlank(proxyUser.getAccountId())) {
            return error("项目ID为空，请联系管理员");
        }

        if (StringUtils.isBlank(proxyUser.getPhone())) {
            return error("请填写APP登录手机号");
        }

        if (!MobileEmailUtils.checkMobileIsOk(proxyUser.getPhone())) {
            return error("请填写合法的手机号");
        }

        // 校验手机号是否被使用
        boolean checkPhone = proxyUserService.checkPhoneExist(proxyUser.getPhone(), AccountTypeEnum.PROJECT.getCode());
        if (checkPhone) {
            return error("该手机号已被占用");
        }


        if (StringUtils.isBlank(proxyUser.getTrueName())) {
            return error("请填写真实姓名");
        }

        if (proxyUser.getIsStaff() == null) {
            return error("请选择是否员工");
        }

        // 主账号只能一个,校验
        if (proxyUser.getIsStaff().intValue() == YesOrNoEnum.NO.getCode().intValue()) {
            boolean checkMain = proxyUserService.checkMainAccount(proxyUser.getAccountId(), AccountTypeEnum.PROJECT.getCode());
            if (checkMain) {
                return error("主账号只能一个！");
            }
        }

        proxyUser.setCreateTime(DateUtils.getNowDate());

        proxyUser.setId(sid.nextShort());// 保存ID
        proxyUser.setAccountType(AccountTypeEnum.PROJECT.getCode());
        return toAjax(proxyUserService.insertProxyUser(proxyUser));
    }


    /**
     * 修改保存项目
     */
    @RequiresPermissions("system:project:edit")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Project project) {

        if (project.getId() == null) {
            return error("主键ID为空");
        }

        if (StringUtils.isBlank(project.getProjectName())) {
            return error("请填写项目名");
        }


        if (StringUtils.isBlank(project.getCompany())) {
            return error("请填写公司名");
        }

        if (project.getDeposit() == null || project.getDeposit().compareTo(BigDecimal.ZERO) <= 0) {
            return error("押金不能为空，且押金不能小于等于0");
        }
        project.setUpdateTime(DateUtils.getNowDate());
        return toAjax(projectService.updateByPrimaryKeySelective(project));
    }

    /**
     * 删除项目
     */
    @RequiresPermissions("system:project:remove")
    @Log(title = "项目", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(projectService.deleteProjectByIds(ids));
    }


    @RequiresPermissions("system:project:delAccount")
    @Log(title = "项目", businessType = BusinessType.DELETE)
    @PostMapping("/delAccount")
    @ResponseBody
    public AjaxResult delAccount(String id) {
        ProxyUser updateProxyUser = new ProxyUser();
        updateProxyUser.setId(id);
        updateProxyUser.setIsDeleted(YesOrNoEnum.YES.getCode());
        updateProxyUser.setUpdateTime(DateUtils.getNowDate());
        return toAjax(proxyUserService.updateByPrimaryKeySelective(updateProxyUser));
    }


}
